package com.vivimice.lotroller.device;

import java.util.HashMap;
import java.util.Map;

import com.vivimice.lotroller.notification.NotificationType;

public abstract class LogicalGate extends Device {

	private Device[] upperDevices;
	
	public LogicalGate(Device[] upperDevices) {
		if (upperDevices.length == 0) {
			throw new IllegalArgumentException();
		}
		
		for (Device upperDevice : upperDevices) {
			if (!upperDevice.hasNextDevice()) {
				upperDevice.setNextDevice(this);
			} else {
				throw new IllegalStateException("Upper device is already associated to another device");
			}
		}
		
		this.upperDevices = upperDevices;
	}

	@Override
	public Map<NotificationType, Object> getDataMap() {
		// data is merged from upper devices
		Map<NotificationType, Object> dataMap = new HashMap<NotificationType, Object>();
		for (Device upperDevice : upperDevices) {
			dataMap.putAll(upperDevice.getDataMap());
		}
		return dataMap;
	}

	protected Device[] getUpperDevices() {
		return upperDevices;
	}
	
	@Override
	public void close() {
		for (Device upperDevice : upperDevices) {
			upperDevice.close();
		}
	}

}
